from sqlalchemy.orm import Session
from sqlalchemy import desc, or_
from typing import List, Optional

from app.models.news import News
from app.schemas.news import NewsCreate, NewsUpdate

class NewsCRUD:
    def create_news(self, db: Session, news_data: NewsCreate, author_id: int) -> News:
        """创建新闻"""
        news_dict = news_data.dict()
        news_dict['author_id'] = author_id  # 设置作者ID
        
        db_news = News(**news_dict)
        db.add(db_news)
        db.commit()
        db.refresh(db_news)
        return db_news
    
    def get_news_by_id(self, db: Session, news_id: int) -> Optional[News]:
        """根据ID获取新闻"""
        return db.query(News).filter(News.id == news_id).first()
    
    def get_news_list(
        self, 
        db: Session, 
        skip: int = 0, 
        limit: int = 20,
        keyword: Optional[str] = None
    ) -> tuple[List[News], int]:
        """获取新闻列表"""
        query = db.query(News)
        
        # 关键词搜索
        if keyword:
            query = query.filter(
                or_(
                    News.title.contains(keyword),
                    News.content.contains(keyword)
                )
            )
        
        # 总数
        total = query.count()
        
        # 排序和分页
        news_list = query.order_by(desc(News.created_at)).offset(skip).limit(limit).all()
        
        return news_list, total
    
    def update_news(self, db: Session, news_id: int, news_data: NewsUpdate) -> Optional[News]:
        """更新新闻"""
        db_news = self.get_news_by_id(db, news_id)
        if not db_news:
            return None
        
        update_data = news_data.dict(exclude_unset=True)
        
        for field, value in update_data.items():
            setattr(db_news, field, value)
        
        db.commit()
        db.refresh(db_news)
        return db_news
    
    def delete_news(self, db: Session, news_id: int) -> bool:
        """删除新闻"""
        db_news = self.get_news_by_id(db, news_id)
        if not db_news:
            return False
        
        db.delete(db_news)
        db.commit()
        return True

# 创建实例
news_crud = NewsCRUD()